<script setup lang="ts">
/**
 * 微信小程序登录页面
 * 支持微信手机号授权登录和登录协议展示
 */

useHideHomeButton();

const appStore = useAppStore();
const authStore = useAuthStore();

/**
 * uView Modal 组件实例类型
 */
interface UvModalInstance {
  /** 打开模态框 */
  open: () => void;
  /** 关闭模态框 */
  close: () => void;
}

const modalRef = ref<UvModalInstance | null>(null);

/**
 * 监听登录协议显示状态
 * 当需要显示协议时自动打开模态框
 */
watch(
  () => authStore.signInAgreement.show,
  (show: boolean) => {
    console.log('登录协议显示状态:', show);

    // 只有当组件已加载且需要显示时才打开模态框
    if (show && modalRef.value) {
      modalRef.value.open();
    }
  },
  { immediate: true }
);

/**
 * 处理协议确认
 */
const handleConfirm = (): void => {
  authStore.agreeAgreement();
};

/**
 * 处理微信手机号授权
 * @param e 微信授权事件对象
 */
const handleGetPhoneNumber = (e: any): void => {
  if (typeChecker.isEmpty(e.detail.code)) {
    console.warn('未获取到手机号授权码');
    return;
  }

  authStore.signInWithMiniProgram({
    phoneCode: e.detail.code,
    type: 6,
  });
};

/**
 * 页面初始化
 * 尝试自动登录
 */
onMounted(() => {
  console.log('登录页面已挂载，尝试自动登录');
  authStore.autoSignIn();
});
</script>

<template>
  <view class="flex flex-col items-center justify-center">
    <!-- 应用Logo -->
    <view class="mt-50" v-if="!authStore.autoLoading">
      <up-image
        src="/static/images/logo.svg"
        shape="circle"
        mode="aspectFill"
        width="100"
        height="100"
      />
    </view>

    <!-- 登录按钮 -->
    <view class="footer" v-if="!authStore.autoLoading">
      <up-button color="#07C160" open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">
        登录授权
      </up-button>
    </view>

    <!-- 加载状态 -->
    <up-loading-page
      :loading="authStore.autoLoading"
      loading-text="加载中"
      loading-mode="spinner"
      :loading-color="appStore.theme.color.primary"
      :color="appStore.theme.color.primary"
      icon-size="32"
    />

    <!-- 登录协议模态框 -->
    <up-modal
      ref="modalRef"
      :title="authStore.signInAgreement.title"
      :show="false"
      @confirm="handleConfirm"
    >
      <scroll-view scroll-y class="h-600rpx">
        <rich-text :nodes="authStore.signInAgreement.content" />
      </scroll-view>
    </up-modal>
  </view>
</template>

<style scoped>
.footer {
  width: calc(100% - 400rpx);
  margin: 80rpx auto 0;
}
</style>
